package com.zhongkeruan.order.service.impl;

import com.codingapi.tx.annotation.TxTransaction;
import com.zhongkeruan.common.constants.StatusCode;
import com.zhongkeruan.common.model.Order;
import com.zhongkeruan.common.model.Product;
import com.zhongkeruan.common.vo.Result;
import com.zhongkeruan.order.dao.OrderDao;
import com.zhongkeruan.order.exception.TimeOutException;
import com.zhongkeruan.order.hystrix.ProductHystrix;
import com.zhongkeruan.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author yangyao
 * @Description: UserServiceImpl
 * @date 2019/1/11 15:13
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ProductHystrix productHystrix;


    public List<Order> getOrderList() throws Exception {
        return orderDao.getOrderList();
    }

    public Order getOrderById(Long id) throws Exception {
        return orderDao.getOrderById(id);
    }

    @Transactional
    public List<Order> getOrderByUserId(Long userId) throws Exception {
        return orderDao.getOrderByUserId(userId);
    }

    @TxTransaction
    @Transactional
    public int addOrder(Order order) throws Exception {
        Product product = new Product();
        product.setPrice(new BigDecimal(new Random().nextInt(10)));
        product.setSpec("小学");
        product.setProductName("语文");
        Result result = productHystrix.addProduct(product);
        if (StatusCode.SUCCESS != result.getCode()){
            throw new TimeOutException(StatusCode.TIMEOUT,"请求超时");
        }
        return orderDao.addOrder(order);
    }
}
